package com.zhongshengnetwork.rightbe.lang.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.expandabletextview.ExpandableTextView;
import com.zhongshengnetwork.rightbe.common.pulluprefresh.xlistview.XListView;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.ThirdDataInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ThirdLangActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private TopBarView topbar;
    private int type;
    private String name;
    private int pageindex = 0;
    private static final int Records = 20;
    private XListView listview;
    private List<ThirdDataInfoModel> list = null;
    private MyAdapter adapter;
    //加载动画
    private AVLoadingIndicatorView avi;
    private List<String> nameList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third_lang);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        type = getIntent().getIntExtra("type",0);
        name = getIntent().getStringExtra("name");
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getTitleView().setText(name);
        pageindex = 0;
        if (list == null){
            list = new ArrayList<ThirdDataInfoModel>();
        }
        if (nameList == null){
            nameList = new ArrayList<String>();
            nameList.add("分享给微信好友");
            nameList.add("分享到微信朋友圈");
            nameList.add("分享给QQ好友");
            nameList.add("分享到QQ空间");
            nameList.add("分享到微博");
        }
        listview=(XListView) findViewById(R.id.third_lang_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("TAG","position="+position);
                if (list == null || list.size() == 0){
                    return;
                }
                int index = position-1;
                while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                    index+=1;
                }
                onClickShare(index);
            }
        });
        listview.setPullRefreshEnable(true);
        listview.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageindex = 0;
                getData();
            }

            @Override
            public void onLoadMore() {
                getData();
            }
        });
        getData();
    }

    private void getData(){

        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                if (CommonUtils.isLogin()){
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                }
                map.put(APIKey.typeKey,""+type);
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, "miniapp/langappid/thirddatalist.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                avi.hide();
                                if (pageindex > 0){
                                    listview.stopLoadMore();
                                }else {
                                    list.clear();
                                    listview.stopRefresh(true);
                                }
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){
                                    List<ThirdDataInfoModel> l = GsonTools.getThirdDataInfoModel(data);
                                    if (l != null && l.size() > 0){
                                        if (l.size() >= Records){
                                            listview.setPullLoadEnable(true);
                                        }else {
                                            listview.setPullLoadEnable(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        listview.setPullLoadEnable(false);
                                    }
                                    pageindex += 1;
                                    adapter.notifyDataSetChanged();
                                }else {
                                    CustomApplication.showTip(commonModel, ThirdLangActivity.this);
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (pageindex > 0){
                                    listview.stopLoadMore();
                                }else {
                                    list.clear();
                                    listview.stopRefresh(true);
                                }
                                avi.hide();
                            }
                        });
                    }
                });
            }
        }.start();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(ThirdLangActivity.this, R.layout.thirddata_listview_item,null);
            }
            View view=convertView;
            TextView data_content = (TextView) view.findViewById(R.id.data_content);
            ThirdDataInfoModel model = list.get(position);
            data_content.setText(model.getContent());
            return view;
        }
    }

    //点击了分享
    private void onClickShare(final int positon){
        if (list == null || list.size() == 0){
            return;
        }
        final ThirdDataInfoModel model = list.get(positon);
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ThirdLangActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : nameList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which == 1){
                        //分享给微信好友
                        shareToWX(1,model.getContent());
                    }else if (which == 2){
                        //分享到朋友圈
                        shareToWX(0,model.getContent());
                    }else if (which == 3){
                        //分享到qq
                        shareToQQ(0,"言微句美，发现共鸣。",model.getContent());
                    }else if (which == 4){
                        //qq空间
                        shareToQQ(0,"言微句美，发现共鸣。",model.getContent());
                    }else if (which == 5){
                        //微博
                        shareToWeiBo(model.getContent());
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type,String title,String content){
        params = new Bundle();
        if (type == 0){//分享给QQ好友
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,"http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe");// 内容地址
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://image.daydayrise.net/360@2x.png");// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(ThirdLangActivity.this, params, null);
                }
            });
        }else {
            //分享到QQ空间
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,"http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe");// 内容地址
            ArrayList<String> imgUrlList = new ArrayList<>();
            imgUrlList.add("http://image.daydayrise.net/360@2x.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);// 图片地址
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQzone(ThirdLangActivity.this, params, null);
                }
            });
        }

    }

    //分享到微博
    private void shareToWeiBo(String content){
        CustomApplication.WbShareType = 2;
        CustomApplication.WbShareSourceId = "";
        CustomApplication.WbShareText = content;
        Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
        //发送广播
        sendBroadcast(mIntent);
    }

    //分享文字到微信
    private void shareToWX(int type, String title){

        WXTextObject textObject = new WXTextObject();
        textObject.text = title;

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObject;
        msg.description = title;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text");
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
